package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.ruoyi.auth.form.Code;
import com.ruoyi.auth.form.UserLoginBody;
import com.ruoyi.auth.utils.SmsUtil;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.context.Theme;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate redisTemplate;
    //短信验证码
    private static Integer smscode;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    //用户端登录
    @PostMapping("userLogin")
    public R<?> userLogin(@RequestBody UserLoginBody form)
    {
        System.out.println(form);

        //判断验证码是否正确
        if (!redisService.hasKey(CacheConstants.CAPTCHA_CODE_KEY+form.getPhone())){
            throw new ServiceException("短信验证码过期!");
        }
        String code = Integer.toString(redisService.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + form.getPhone()));
        String ercode = form.getCode();
        if(!ercode.equals(code)) {
        throw new ServiceException("短信验证码错误!");
    }
        // 用户登录
        //错误！
        LoginUser userInfo = sysLoginService.userLogin(form.getPhone(), form.getCode());
        System.out.println("--------------");
        System.out.println(userInfo);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }
    //发送验证码
    @PostMapping("getCode")
    public R<?> getCode(@RequestBody String phone)
    {
        System.out.println(phone);
        //手机号校验
        if(!Pattern.compile("^1[3-9]\\d{9}$").matcher(phone).matches()) {
            return R.fail("请输入正确的手机号!");
        }
        //随机生成验证码 4位
        smscode = new Random().nextInt(9000)+1000;
        redisTemplate.opsForValue().set(CacheConstants.CAPTCHA_CODE_KEY+phone, smscode, 3, TimeUnit.HOURS);
        //"您的验证码为：" + smscode + "，有效期3分钟，请妥善保管。"
        SmsUtil.sendSms(phone,"阿里云短信测试" , "SMS_154950909", JSON.toJSONString(new Code(smscode)));

        System.out.println(smscode);
        System.out.println("ok"+R.ok());
        return R.ok();
    }


}
